<template>
  <div>
    <el-icon
      class="hover:cursor-pointer hover:text-[var(--theme-color)]"
      title="复制"
      @click="copyToClipboard(content)"
      :size="18"
    >
      <CopyDocument />
    </el-icon>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";

const props = defineProps({
  // 要复制的文本
  text: {
    type: String,
    required: true,
  },
});

const content = ref("");
/**
 * 复制文本到剪贴板
 * @param {string} text - 要复制的文本
 * @param {Object} options - 配置选项
 * @param {number} options.successDuration - 成功提示持续时间（毫秒）
 * @returns {Promise<{status: 'success'|'error', message: string}>} - 复制结果
 */
async function copyToClipboard(text, options = {}) {
  const { successDuration = 2000 } = options;

  // 检查是否支持现代 Clipboard API
  if (navigator.clipboard) {
    try {
      await navigator.clipboard.writeText(text);
      return ElMessage.success("复制成功");
    } catch (error) {
      ElMessage.error("现代剪贴板API复制失败");
    }
  }

  // 旧版方法：创建临时文本域并使用 execCommand
  const textarea = document.createElement("textarea");
  textarea.value = text;

  // 隐藏文本域
  textarea.style.position = "fixed";
  textarea.style.opacity = "0";

  document.body.appendChild(textarea);
  textarea.select();

  try {
    const result = document.execCommand("copy");
    document.body.removeChild(textarea);

    if (result) {
      return ElMessage.success("复制成功");
    } else {
      return ElMessage.error("复制失败，请手动复制");
    }
  } catch (error) {
    // console.error("旧版剪贴板方法复制失败:", error);
    document.body.removeChild(textarea);
    return ElMessage.error("复制失败，请手动复制");
  }
}

let cleanup;
onMounted(() => {
  cleanup = watchStorage("refresh_copy_text", (e) => {
    content.value = e.data.text;
  });

  // 组件卸载时清理监听
  return () => cleanup();
});

onBeforeUnmount(() => {
  cleanup();
});
</script>

<style scoped>
</style>